{% extends "../base_adminlte.html" %}
{% block content %}
<div class="content-wrapper">
    <div id='checks' style="float:left;overflow-y: scroll ;width: 25%;height: 100%;margin-left: 1.5%;border: 1px #000000">
       <div class="form-group">
          <label>系统列表</label>
          <select name="systems" id='systems' class="form-control">
              <option value="None">请选择系统</option>
              {% for g in systems %}
                  {% if g == system %}
                    <option value={{ g }} selected> {{ g }} </option>
                  {% else %}
                      <option value={{ g }}>
                          {{ g }}
                      </option>
                  {% endif %}
              {% endfor %}
          </select>
       </div>
        <div id="searchTree"></div>
    </div>
    <div style="float:right;width:73%;height: 100%;border: 1px #000000">
        <div  class="row" >
            <div class="col-sm-3">
                <div class="form-group">
                  <label for="exampleInputPassword1">playbooks</label>
                  <select class="form-control select2" style="width: 100%;" id="playbook" name="playbook">
                      <option value="None">选择一个playbook</option>
                      {% for f in playbooks %}
                          {% if f.playbook == sldpb %}
                             <option value={{ f.playbook }} selected> {{ f.nickName|default:f.playbook }} </option>
                         {% else %}
                              <option value="{{ f.playbook }}">{{ f.nickName|default:f.playbook }}</option>
                          {% endif %}
                      {% endfor %}
                  </select>
                </div>
            </div>
            <div class="col-sm-9">
                <div class="row">
                  <div class="col-4">
                    <div class="form-group">
                      <label for="exampleInputPassword1">become用户</label>
                      <input class="form-control" type="text"  id="become_user"  name="become_user"  autocomplete="off">
                    </div>
                  </div>
                     <div class="col-4">
                    <div class="form-group" >
                      <label for="exampleInputPassword1">become密码</label>
                      <input class="form-control" type="password"  id="become_pass"  name="become_pass"  autocomplete="off">
                    </div>
                  </div>
                </div>
                <div style="width: 100%">
                    <div class="form-group">
                      <h4>输入playbook所需要的内部参数</h4>
                      <textarea style="width: 100%;margin-bottom: 3%" type="text" class="form-control" id="vars" name="vars" rows=6 placeholder="{'demo': '请输入字典形式'}"></textarea>
                     </div>
                </div>
             </div>
        <div class="col-sm-12">
        <button style="margin-left: 1.5%" type="button" id="push" class="btn btn-default">提交</button><input type="checkbox" id="confirm" style="margin-left: 50px;"> 🔐&nbsp提交锁，防止误提交。
        </div>
        <div class="col-sm-12" >
          <hr style="height:1px;border:none;border-top:1px solid #555555;">
              <button id="check_playbook" class="btn btn-default">查看选中PlayBook</button>
              <button id="check_hostip" class="btn btn-default" onclick="chkhost()" >查看选中服务器</button>
              <button id="close_win" class="btn btn-default" >关闭信息窗口</button><br>
              <textarea style="height:500px" readonly="readonly"  type="text" id="info" class="form-control" name="info"  rows="8" ></textarea>
        </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scriptcontent %}
<script src="/static/ansible/js/bootstrap-treeview.js"></script>
<!-- Select2 -->
<script src="/static/adminlte/plugins/select2/js/select2.full.min.js"></script>
 <script>
  $(function () {
      //Initialize Select2 Elements
      $('.select2').select2()
  })
  var nodeCheckedSilent = false;
  function nodeChecked(event, node) {
   if (nodeCheckedSilent) {
    return;
   }
   nodeCheckedSilent = true;
   //checkAllParent(node);
   checkAllSon(node);
   nodeCheckedSilent = false;
  }
  var nodeUncheckedSilent = false;
  function nodeUnchecked(event, node) {
   if (nodeUncheckedSilent)
    return;
   nodeUncheckedSilent = true;
   //uncheckAllParent(node);
   uncheckAllSon(node);
   nodeUncheckedSilent = false;
  }
  //选中node时，勾选check
  function sltChecked(event, node){
      $( '#searchTree' ).treeview( 'toggleNodeChecked' , [ node.nodeId, { silent:  true  } ]);
      if (node.state.checked){
          if (nodeUncheckedSilent)
             return;
          nodeUncheckedSilent = true;
          uncheckAllParent(node);
          uncheckAllSon(node);
          nodeUncheckedSilent = false;
      } else {
          if (nodeCheckedSilent) {
            return;
           }
          nodeCheckedSilent = true;
          checkAllParent(node);
          checkAllSon(node);
          nodeCheckedSilent = false;
      }
  }
  //选中全部父节点
  function checkAllParent(node) {
   $('#searchTree').treeview('checkNode', node.nodeId, {
    silent: true
   });
   var parentNode = $('#searchTree').treeview('getParent', node.nodeId);
   if (!("nodeId" in parentNode)) {
    return;
   } else {
    checkAllParent(parentNode);
   }
  }
  //取消全部父节点
  function uncheckAllParent(node) {
   $('#searchTree').treeview('uncheckNode', node.nodeId, {
    silent: true
   });
   var siblings = $('#searchTree').treeview('getSiblings', node.nodeId);
   var parentNode = $('#searchTree').treeview('getParent', node.nodeId);
   if (!("nodeId" in parentNode)) {
    return;
   }
   var isAllUnchecked = true; //是否全部没选中
   for (var i in siblings) {
    if (siblings[i].state.checked) {
     isAllUnchecked = false;
     break;
    }
   }
   if (isAllUnchecked) {
    uncheckAllParent(parentNode);
   }
  }
  //级联选中所有子节点
  function checkAllSon(node) {
   $('#searchTree').treeview('checkNode', node.nodeId, {
    silent: true
   });
   if (node.nodes != null && node.nodes.length > 0) {
    for (var i in node.nodes) {
     checkAllSon(node.nodes[i]);
    }
   }
  }
  //级联取消所有子节点
  function uncheckAllSon(node) {
   $('#searchTree').treeview('uncheckNode', node.nodeId, {
    silent: true
   });
   if (node.nodes != null && node.nodes.length > 0) {
    for (var i in node.nodes) {
     uncheckAllSon(node.nodes[i]);
    }
   }
  }
  //初始化服务器树状选项
  $('#searchTree').treeview({
       showCheckbox: true,
       data: {{ hosttree|safe }},
       onNodeChecked: nodeChecked,
       onNodeUnchecked: nodeUnchecked,
       onNodeSelected: sltChecked
      });
  //根据选中系统跳转页面
  $("#systems").change(function () {
      let sys = $(this).val()
      let selectedpb = $('#playbook').val()
      s = encodeURIComponent(sys) ;
      window.location.href = "/ansible/edit_task/2?systems="+s+"&sldpb="+selectedpb;
  });
  $('#push').click(function(){
          if($("select[name='playbook'] option:selected")[0].value=="None"){
              alert('必须选择一个操作组')
              return false    // 阻止提交
          }else if(document.getElementById('confirm').checked){
              sendtask();
          }else{
              alert('请打开锁 🔐')
              return false
          }
  });
  $('#check_playbook').click(function(){
    document.getElementById("info").style.visibility="visible";
        $.ajax({
            url: '/ansible/get_playbook/',
            data:{"playbook":$('#playbook').val()},
            type: 'GET',
            dataType: 'json',
            success: function(data){
               $('#info').val(data);
            },
        });
    });
  $('#close_win').click(function(){
    document.getElementById("info").style.visibility="hidden";
  })
  function chkhost(){
      var snodes =  $('#searchTree').treeview('getChecked');
      let hosts = []
      for(let i=0;i<snodes.length;i++){
          let s = snodes[i].text.split("__")[1]
          if (s) {
            hosts.push(s)
            hosts.push(' || ')
          }
      }
      document.getElementById("info").style.visibility="visible";
      $('#info').val(hosts);
  }
  function sendtask() {
      var snodes =  $('#searchTree').treeview('getChecked');
      let hosts = []
      for(let i=0;i<snodes.length;i++){
          let s = snodes[i].text.split("__")[1]
          if (s) {
            hosts.push(s)
          }
      }
      let s = '/ansible/edit_task/1'
     $.ajax({
            url: '/ansible/sendtask',
            data: { "remote_user":$('#remote_user').val(),
                "systemname": $('#systems').val(),
                "remote_pass":$('#remote_pass').val(),
                "playbook": $("#playbook").val(),
                "become_user":$('#become_user').val(),
                "become_pass":$('#become_pass').val(),
                "hostlist": JSON.stringify(hosts),
                "vars":JSON.stringify($('#vars').val())
            },
            type: 'POST',
            dataType: 'json',
            async : false,
            success:function (data){
               let a = data;
               {#alert(a)#}
               s="/ansible/task/"+a+"/"
             },
        });
        window.location.href=s ;
  }
</script>
{% endblock %}